import axios from "axios";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
// import local from '@/utils/local.js'
// 创建axios实例
const service = axios.create({
  // baseURL: 'http://23.210.23.1:8081/smart_edu_gov',   // api 的 base_url import.meta.env.VITE_APP_API_PREFIX_URL
  // baseURL: "/api",
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 12000, // 请求超时时间http://172.24.4.166:8088/cq-user-center
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    config.headers.accesstoken = localStorage.getItem("accessToken") ?? "";
    return config;
  },
  function (err) {
    return Promise.reject(err);
  }
);

// 响应拦截器
service.interceptors.response.use(
  function (response) {
    // console.log(response)
    if (response.data.code === 200) {
      return response;
    } else {
      if (response.data.code == 500) {
        // ElMessage.error('token过期,请重新登录')
        console.log("token过期,请重新登录", response);
        // local.remove('TokenKey') //清空token
        localStorage.setItem("accessToken", "");
        // router.push("/login");
        window.parent.location.href = "#/login";
        return response;
      } else if (response.data.code == 3) {
        // ElMessage.error('系统错误，请稍候再试！')
        return response;
      } else if (response?.data.code) {
        // ElMessage.error(response.data?.message)
        return response;
      } else {
        return response;
      }
    }
  },
  function (err) {
    console.log("err", err);
    let { message } = err;
    if (message === "Network Error") {
      message = "网络连接失败";
    } else if (message.includes("timeout")) {
      message = "网络超时";
    } else if (message.includes("Request failed with status code")) {
      // window.parent.location.href = "#/login";
      message = "请求失败";
    }
    // ElMessage.error(message)
    return Promise.reject(err); //超时不重新请求
  }
);

function request(url, method = "get", data = {}, headers) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: method,
      headers: {
        "Content-Type": "application/json",
        // "Content-Type": "application/x-www-form-urlencoded",
        ...headers,
      },
      ...data,
    })
      .then((res) => {
        //成功
        resolve({
          code: res.data.code || res.status,
          data: res.data.data || res.data,
          message: res.data.message,
        });
      })
      .catch((res) => {
        //失败
        reject(res);
      });
  });
}

function upload(url, method = "post", data = {}) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: method,
      headers: {
        "Content-Type": "multipart/form-data",
      },
      data,
    })
      .then((res) => {
        //成功
        resolve({
          code: res.data.code,
          data: res.data.data,
          message: res.data.message,
        });
      })
      .catch((res) => {
        //失败
        reject(res);
      });
  });
}

function downloadFile(
  url,
  method,
  params,
  headers = { "Content-Type": "application/json" }
) {
  return new Promise((resolve, reject) => {
    service({
      url: url,
      method: method ? method : "get",
      headers,
      responseType: "blob",
      ...params,
    })
      .then((res) => {
        if (
          res.data.success === undefined &&
          res.data.type === "application/json"
        ) {
          const fileReader = new FileReader();
          fileReader.readAsText(res.data, "utf-8");
          fileReader.onload = function () {
            const result = JSON.parse(fileReader.result);
            console.log("result", result);
            if (result.code !== 0) {
              // ElMessage.error(result.message)
              reject(res);
            }
          };
        } else {
          //成功
          resolve(res);
        }
      })
      .catch((res) => {
        //失败
        reject(res);
      });
  });
}
export default {
  request,
  upload,
  downloadFile,
  service,
};
